const dbUtil = require('../util/dbutil')
const {  AssertUtils } = require("../util/utils");
const validation = require('../util/Validation')

// 添加维保列表
const addPlanList = async(body) => {
    const res = await validation.theFieldIsMissingExists(body, ["replacement_parts","category","price","total_price","date"])
    AssertUtils.isFalse(res, res)
    return await dbUtil.exec(`INSERT INTO maintenance_plan(replacement_parts,category,price,total_price,date) VALUES (?, ?, ?, ?, ?)`, 
    [body.replacement_parts,body.category,body.price,body.total_price,body.date])
}

// 修改维保列表
const updatePlanList = async(body)=>{
    const res = await validation.theFieldIsMissingExists(body, ["replacement_parts","category","price","total_price","date","id"])
    AssertUtils.isFalse(res, res)
    return await dbUtil.exec(`UPDATE maintenance_plan SET replacement_parts=?,category=?,price=?,total_price=?,date=? where id = ?`, 
    [body.replacement_parts,body.category,body.price,body.total_price,body.date,body.id])
}

// 删除维保列表
const delPlanList = async(body)=>{
    const res = await validation.theFieldIsMissingExists(body, ['id'])
    AssertUtils.isFalse(res, res)
    const result = await dbUtil.exec(`DELETE FROM maintenance_plan WHERE id = ${body.id}`)
}

// 查询维保列表
const getPlanList = async(replacement_parts=null,category=null,price=null,total_price=null,date=null)=>{
    console.log(replacement_parts,category,price,total_price,date);
    if (replacement_parts === null && category === null && price === null && total_price === null && date === null) {
        return await dbUtil.getAll(`select * from maintenance_plan`)
    } else {
        return await dbUtil.getAll(`
   select * from maintenance_plan 
   where replacement_parts like concat('%',?,'%') or category like concat('%',?,'%') 
   or price like concat('%',?,'%') or total_price like concat('%',?,'%') or date like concat('%',?,'%')
   `, [replacement_parts,category,price,total_price,date])
    }
}


module.exports = {
    addPlanList,
    updatePlanList,
    delPlanList,
    getPlanList
}